<?php abstract class Auth implements ifAuth {
	protected static $User = '';
	protected static $Group = '';
	protected static $PermModsUsers = array ('modAuth'); // module class names that should be executable by users
	protected static $PermModsAnon = array ('modAuth'); // module class names that should be executable by anonymous
	protected static $PermViewUsers = array ('not-logged-in'); // view names that should be accessible by users
	protected static $PermViewAnon = array ('not-logged-in'); // view names that should be accessible by anonymous

	protected static function Inherit () {
		$User = XReq::Fetch ('User');
		$User and self::$User = $User;
	}
	protected static function GrLookup () {if ($User = self::User ()) self::$Group = ('admin' === $User) ? 'admins' : 'users';}
	public static function User () {
		self::$User or self::Inherit ();
		return (self::$User);
	}
	public static function Group () {
		self::$Group or self::GrLookup ();
		return (self::$Group);
	}
	public static function Login ($Username) {XReq::Write ('User', $Username);}
	public static function Logout () {
		self::$User = '';
		XReq::Drop ('User');
	}
	public static function Check ($Username, $Password) {
		global $PG;
		if ('admin' === $Username) return ('admin' === $Password);
		if (! $PG->FetchValue ('select "Username" from "Users" where "Username" = %S;', $Username)) return (FALSE);
		$LDAP = ldap_connect ('195.151.207.13') or die ('ldap connection failed');
		ldap_set_option ($LDAP, LDAP_OPT_PROTOCOL_VERSION, 3);
		$Result = ldap_get_entries ($LDAP, ldap_search ($LDAP, 'dc=naumen,dc=ru', "(uid=$Username)", array ('dn'), 1));
		if (isset ($Result ['count']) and $Result ['count']) return (ldap_bind ($LDAP, $Result [0]['dn'], $Password));
	}
	public static function Permission ($Class = 'module', $View = NULL) {
		switch ($Class) {
			case 'module':
				$Caller = debug_backtrace ();
				if (isset ($Caller [1]['class'])) {
					$Caller = $Caller [1]['class'];
					if ($Group = self::Group ()) switch ($Group) {
						case 'admins': return (TRUE);
						case 'users': return (in_array ($Caller, self::$PermModsUsers));
					} else return (in_array ($Caller, self::$PermModsAnon)); 
				}
			break;
			case 'view':
				if ($View and $Group = self::Group ()) switch ($Group) {
					case 'admins': return (TRUE);
					case 'users': return (in_array ($View, self::$PermViewUsers));
				} else return (in_array ($View, self::$PermViewAnon)); 
			break;
		}
		return (FALSE);
	}
	public static function DefaultView () {
		if ($Group = self::Group ()) switch ($Group) {
			case 'admins': return ('admin');
			case 'users': return ('user');
			default: return ('unknown-group');
		} else return ('not-logged-in');
	}
}